const { Router } = require('express');
const express = require('express');
const router = express.Router();
const User = require('../db/model/userModel');
const Mail = require('../utils/mail');


let codes = {}; // 用来保存验证码
let ctime = 0;
/**
 * @api {post} /user/reg 用户注册
 * @apiName 用户注册
 * @apiGroup User
 *
 * @apiParam {String} us 用户名
 * @apiParam {String} ps 用户密码
 * @apiParam {String} code 验证码
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
// 注册接口
router.post('/reg', async (req, res, code) => {
  //获取数据
  try {
    let { us, ps, code} = req.body;
    if (us && ps && code) {
      // return res.send({ code: 200, msg: '参数错误' });
      if (codes[us] != code) {
        return res.send({ code: 200, msg: '验证码错误' });
      }
      let data = await User.find({ us });
      if (0 === data.length) {
        // 用户名不存在,可以注册
        await User.insertMany({ us, ps });
        return res.send({ code: 200, msg: '注册成功' });
      } else {
        return res.send({ code: 200, msg: '用户已存在' });
      }
    }
  } catch (e) {
    res.send({ code: 200, msg: '注册失败' });
  }

  //处理数据
  //返回数据
});
/**
 * @api {post} /user/login 用户登录
 * @apiName login
 * @apiGroup User
 *
 * @apiParam {String} us 用户名
 * @apiParam {String} ps 用户密码
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
// 登录接口    // 一个用的async/await一个是.then帮助区分.
router.post('/login', (req, res) => {
  let { us, ps } = req.body;
  if (!us || !ps) {
    return res.send({ err: -1, msg: '参数错误' });
  }

  User.find({ us, ps })
    .then((data) => {
      if (data.length > 0) {
        res.send({ err: 0, msg: '登录成功' });
      } else {
        res.send({ err: -2, msg: '用户名或者密码不正确' });
      }
      console.log(data);
    })
    .catch((err) => {
      return res.send({ err: -2, msg: '内部错误' });
    });
});
/**
 * @api {post} /user/getMailCode 发送验证码
 * @apiName 发送验证码
 * @apiGroup User
 *

 * @apiParam {String} mail 邮箱
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
// 发送邮箱验证码接口
router.post('/getMailCode', async (req, res) => {
  try {
    let { mail } = req.body;
    let code = parseInt(Math.random() * 10000);
    
    
    //为了比较 用一个临时变量
    let t = new Date().getTime();

    if(t-ctime<300000){
      // 报错,5分钟以后再试.
      return res.send({ code: 200, msg: '请五分钟后再试' });
    }
    
    ctime = t;

    await Mail.send(mail, code); //这个返回不是promise对象,需要封装一下
    codes[mail] = {ctime,code};
    
    console.log(codes);
    res.send({ code: 200, msg: '验证码发送成功' });
  } catch (e) {
    console.log(e);
    res.send({ code: 200, msg: '验证码发送失败' });
  }
});

module.exports = router;
